package io.bhex.app.account.ui;

import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.bhex.app.R;
import io.bhex.app.account.adapter.AssetListAdapter;
import io.bhex.app.account.presenter.SubAccountPresenter;
import io.bhex.app.account.utils.AccountUtil;
import io.bhex.app.base.BaseActivity;
import io.bhex.app.utils.CommonUtil;
import io.bhex.app.utils.IntentUtils;
import io.bhex.app.utils.NumberUtils;
import io.bhex.app.view.ShadowDrawable;
import io.bhex.app.view.TopBar;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.core.SPEx;
import io.bhex.baselib.utils.DebugLog;
import io.bhex.baselib.utils.PixelUtils;
import io.bhex.baselib.view.alertview.AlertView;
import io.bhex.sdk.account.bean.SubAccountBean;
import io.bhex.sdk.account.bean.SubAccountListResponse;
import io.bhex.sdk.data_manager.RateDataManager;
import io.bhex.sdk.data_manager.SymbolDataManager;
import io.bhex.sdk.quote.bean.QuoteTokensBean;
import io.bhex.sdk.trade.bean.AssetListResponse;

import static io.bhex.baselib.constant.AppData.HIDE_MIN_BTC;

/**
 * ================================================
 * 作   者：ppzhao
 * 创建时间：2019-10-30
 * 邮   箱：
 * 描   述：
 * ================================================
 */

public class SubAccountActivity extends BaseActivity<SubAccountPresenter, SubAccountPresenter.SubAccountUI> implements SubAccountPresenter.SubAccountUI, CompoundButton.OnCheckedChangeListener, View.OnClickListener, OnRefreshListener {

    private TopBar topBar;
    private boolean isOpenEye;
    private TextView totalAssetTitleTx;
    private TextView totalAssetTx;
    private TextView totalAssetCurrencyTx;
    private SmartRefreshLayout swipeRefresh;
    private CheckBox eyeCheckbox;
    private RecyclerView recyclerView;

    private List<AssetListResponse.BalanceBean> mTokenList = new ArrayList<>();
    private AssetListAdapter assetListAdapter;
    private EditText searchEditText;
    private CheckBox visibleSmallAmountCheckBox;
    private SubAccountBean currentSubAccount;

//    private ArrayList<AccountTypeBean> accountTypeList = new ArrayList<>();
    private ArrayList<SubAccountBean> subAccountList = new ArrayList<>();
    private TextView accountTypeTx;
    private AssetListResponse mAllAssetResponse;


    @Override
    protected int getContentView() {
        return R.layout.activity_sub_account_layout;
    }

    @Override
    protected SubAccountPresenter createPresenter() {
        return new SubAccountPresenter();
    }

    @Override
    protected SubAccountPresenter.SubAccountUI getUI() {
        return this;
    }

    @Override
    protected int setStatusBarColor() {
        return getResources().getColor(R.color.blue);
    }

    @Override
    protected void initView() {
        super.initView();
        topBar = viewFinder.find(R.id.topBar);
        topBar.setLeftImg(CommonUtil.isBlackMode() ? R.mipmap.white_back : R.mipmap.white_back);

        accountTypeTx = viewFinder.find(R.id.accountType);
        totalAssetTitleTx = viewFinder.find(R.id.asset_total_txt);
        totalAssetTx = viewFinder.find(R.id.asset_total);
        totalAssetCurrencyTx = viewFinder.find(R.id.asset_total_currency);
        swipeRefresh = viewFinder.find(R.id.swipeRefresh);
        eyeCheckbox = viewFinder.find(R.id.asset_eye);

        LayoutInflater layoutInflater = LayoutInflater.from(this);

        recyclerView = viewFinder.find(R.id.recyclerView);
        assetListAdapter = new AssetListAdapter(mTokenList);
        //assetListAdapter.addHeaderView(headerView);

        View bb_emptyView = layoutInflater.inflate(R.layout.empty_layout, swipeRefresh, false);
        ViewGroup.LayoutParams layoutParams = bb_emptyView.getLayoutParams();
        layoutParams.height = PixelUtils.dp2px(300);
        bb_emptyView.setLayoutParams(layoutParams);
        assetListAdapter.setHeaderAndEmpty(true);
        assetListAdapter.setEmptyView(bb_emptyView);

        assetListAdapter.isFirstOnly(false);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(assetListAdapter);
        searchEditText = viewFinder.find(R.id.search_edit);
        ShadowDrawable.setShadow(searchEditText);
        searchEditText.clearFocus();
        totalAssetTx.requestFocus();
        visibleSmallAmountCheckBox = viewFinder.find(R.id.visibleSmallAmountCheckBox);

    }

    @Override
    protected void addEvent() {
        super.addEvent();
        swipeRefresh.setOnRefreshListener(this);
        topBar.setTitleOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSubAccountSelect();
            }
        });

        viewFinder.find(R.id.transferBtn).setOnClickListener(this);
        viewFinder.find(R.id.subAcountBtn).setOnClickListener(this);
        eyeCheckbox.setOnCheckedChangeListener(this);
        visibleSmallAmountCheckBox.setOnCheckedChangeListener(this);
        searchEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                search(s.toString().trim(), visibleSmallAmountCheckBox.isChecked());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    /**
     * 子账户类别
     */
    private void showSubAccountSelect() {
        closeKeyBoard(searchEditText);
        final ArrayList<String> currentSelectList = new ArrayList<>();
        if (subAccountList != null) {
            for (SubAccountBean accountBean : subAccountList) {
                currentSelectList.add(accountBean.getAccountName());
            }
        }
        if (currentSelectList != null&&currentSelectList.size()>0) {
            AlertView.showSheet(this, currentSelectList, getString(R.string.string_alert_title_select_sub_account_type), null, getString(R.string.string_cancel), new AlertView.DialogListener() {
                @Override
                public void onShow(final AlertView alert) {

                }

                @Override
                public void onDissmiss(AlertView alert) {

                }

                @Override
                public void onItemClick(int position, String item) {
                    if (position == -1) {
                        return;
                    }

                    if (subAccountList != null) {
                        if (position < subAccountList.size()) {
                            SubAccountBean accountBean = subAccountList.get(position);
                            setCurrentAccount(accountBean);
                        }
                    }
                }
            });
        }else{
            DebugLog.e("current can set levers is null");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        isOpenEye = SPEx.get(AppData.SPKEY.ASSET_EYE_SWITCHER, true);
        eyeCheckbox.setChecked(isOpenEye);
    }

    @Override
    public void showAccountList(SubAccountListResponse response) {
        if (response != null) {
            List<SubAccountBean> accountList = response.getArray();
            ArrayList<SubAccountBean> subAccountList = handleAccountListData(accountList);
            if (subAccountList != null && subAccountList.size() > 0) {
                viewFinder.find(R.id.subAccountTips).setVisibility(View.GONE);
                viewFinder.find(R.id.assetListTop).setVisibility(View.VISIBLE);
                viewFinder.find(R.id.recyclerView).setVisibility(View.VISIBLE);

                if (currentSubAccount == null) {
                    SubAccountBean firstSubAccountBean = subAccountList.get(0);
                    if (firstSubAccountBean != null) {
                        setCurrentAccount(firstSubAccountBean);
                    }
                }else{
                    getPresenter().getAccountAsset(currentSubAccount);
                }

            } else {
                topBar.setTitle(getString(R.string.string_not_sub_account));
                viewFinder.find(R.id.subAccountTips).setVisibility(View.VISIBLE);
                viewFinder.find(R.id.assetListTop).setVisibility(View.GONE);
                viewFinder.find(R.id.recyclerView).setVisibility(View.GONE);
            }
        }
    }

    /**
     * 过滤主账户，获取子账户列表
     * @param accountList
     * @return
     */
    private ArrayList<SubAccountBean> handleAccountListData(List<SubAccountBean> accountList) {
        subAccountList.clear();
        if (accountList != null && accountList.size()>0) {
            for (SubAccountBean accountBean : accountList) {
                int accountIndex = accountBean.getAccountIndex();
                if (accountIndex!=0) {
                    subAccountList.add(accountBean);
                }
            }
        }

        return subAccountList;
    }

    private void setCurrentAccount(SubAccountBean subAccountBean) {
        if (subAccountBean != null) {
            if (currentSubAccount != null) {
                if (currentSubAccount.getAccountId() == subAccountBean.getAccountId()) {
                    return;
                }else{
                    clearView();
                }
            }

            currentSubAccount = subAccountBean;
            String accountName = subAccountBean.getAccountName();
            if (!TextUtils.isEmpty(accountName)) {
                topBar.setTitle(accountName);
            }
            accountTypeTx.setText(AccountUtil.getAccountTypeName(this,currentSubAccount.getAccountType()));
            getPresenter().getAccountAsset(subAccountBean);
        }
    }

    private void clearView() {
        accountTypeTx.setText(getString(R.string.string_placeholder));
        totalAssetTx.setText(getString(R.string.string_placeholder));
        totalAssetCurrencyTx.setText(getString(R.string.string_placeholder));
        allTokensBalance.clear();
        assetListAdapter.setNewData(allTokensBalance);
        searchEditText.setText("");
    }

    HashMap<String, AssetListResponse.BalanceBean> hasBalanceMap = new HashMap<>();
    List<AssetListResponse.BalanceBean> allTokensBalance = new ArrayList<>();
    List<AssetListResponse.BalanceBean> filterList = new ArrayList<>();

    @Override
    public void showAccountAsset(SubAccountBean subAccountBean, AssetListResponse allAssetResponse) {
        if (allAssetResponse != null) {
            mAllAssetResponse = allAssetResponse;
            setTopTotalAsset(mAllAssetResponse);

            hasBalanceMap.clear();
            allTokensBalance.clear();
            List<AssetListResponse.BalanceBean> hasBalanceList = mAllAssetResponse.getBalance();
            if (hasBalanceList != null && hasBalanceList.size() > 0) {
                for (AssetListResponse.BalanceBean balanceBean : hasBalanceList) {
                    hasBalanceMap.put(balanceBean.getTokenId(), balanceBean);
                }
            }

            int accountType = subAccountBean.getAccountType();
            if (accountType == 1) {//币币
                List<QuoteTokensBean.TokenItem> tokenList = SymbolDataManager.GetInstance().getTokenList();
                if (tokenList != null && tokenList.size() > 0) {
                    for (QuoteTokensBean.TokenItem tokenItem : tokenList) {
                        if (tokenItem != null) {
                            String tokenId = tokenItem.getTokenId();
                            if (!TextUtils.isEmpty(tokenId)) {
                                AssetListResponse.BalanceBean balanceBean = hasBalanceMap.get(tokenId);
                                if (balanceBean != null) {
                                    allTokensBalance.add(balanceBean);
                                } else {
                                    AssetListResponse.BalanceBean newEmptyBalance = new AssetListResponse.BalanceBean();
                                    newEmptyBalance.setTokenId(tokenId);
                                    newEmptyBalance.setTokenName(tokenItem.getTokenName());
                                    newEmptyBalance.setTokenFullName(tokenItem.getTokenFullName());
                                    allTokensBalance.add(newEmptyBalance);
                                }
                            }
                        }

                    }
                }

                assetListAdapter.setNewData(allTokensBalance);

            } else if (accountType == 2) {//期权
                List<String> optionCoinToken = SymbolDataManager.GetInstance().getOptionCoinToken();
                if (optionCoinToken != null && optionCoinToken.size() > 0) {
                    for (String tokenId : optionCoinToken) {
                        if (!TextUtils.isEmpty(tokenId)) {
                            AssetListResponse.BalanceBean balanceBean = hasBalanceMap.get(tokenId);
                            if (balanceBean != null) {
                                allTokensBalance.add(balanceBean);
                            } else {
                                AssetListResponse.BalanceBean newEmptyBalance = new AssetListResponse.BalanceBean();
                                newEmptyBalance.setTokenId(tokenId);
                                newEmptyBalance.setTokenName(tokenId);
                                newEmptyBalance.setTokenFullName(tokenId);
                                allTokensBalance.add(newEmptyBalance);
                            }
                        }

                    }
                }

                assetListAdapter.setNewData(allTokensBalance);
            } else if (accountType == 3) {//合约
                List<String> futuresCoinToken = SymbolDataManager.GetInstance().getFuturesCoinToken();

                if (futuresCoinToken != null && futuresCoinToken.size() > 0) {
                    for (String tokenId : futuresCoinToken) {
                        if (!TextUtils.isEmpty(tokenId)) {
                            AssetListResponse.BalanceBean balanceBean = hasBalanceMap.get(tokenId);
                            if (balanceBean != null) {
                                allTokensBalance.add(balanceBean);
                            } else {
                                AssetListResponse.BalanceBean newEmptyBalance = new AssetListResponse.BalanceBean();
                                newEmptyBalance.setTokenId(tokenId);
                                newEmptyBalance.setTokenName(tokenId);
                                newEmptyBalance.setTokenFullName(tokenId);
                                allTokensBalance.add(newEmptyBalance);
                            }
                        }

                    }
                }
                assetListAdapter.setNewData(allTokensBalance);

            }

        }
    }

    /**
     * 设置顶部总资产
     *
     * @param mAllAssetResponse
     */
    private void setTopTotalAsset(AssetListResponse mAllAssetResponse) {
        if (mAllAssetResponse == null) {
            return;
        }
        //TODO 此处取值是BTC估值 v2.0.2调整的
        String totalAsset = NumberUtils.roundFormatDown(mAllAssetResponse.getBtcValue(), AppData.Config.DIGIT_DEFAULT_VALUE);
        String legalMoney = RateDataManager.CurRatePrice(AppData.Config.LEGAL_MONEY_ABOUT_VALUE_CAL_UNIT, totalAsset);
        legalMoney = RateDataManager.getShowLegalMoney(legalMoney, AppData.DIGIT_LEGAL_MONEY);

        totalAssetTitleTx.setText(getString(R.string.string_total_asset_about));
        if (isOpenEye) {
            totalAssetTx.setText(totalAsset);
            totalAssetCurrencyTx.setText("≈" + legalMoney);
        } else {
            totalAssetTx.setText(getString(R.string.string_star_star));
            totalAssetCurrencyTx.setText(getString(R.string.string_star_star));
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.asset_eye:
                switchEye(isChecked);
                break;
            case R.id.visibleSmallAmountCheckBox:
                String searchContent = searchEditText.getText().toString().trim();
                search(searchContent, isChecked);
                break;
        }
    }

    /**
     * 设置开闭眼资产
     *
     * @param isOpenEye
     */
    private void switchEye(boolean isOpenEye) {
        SPEx.set(AppData.SPKEY.ASSET_EYE_SWITCHER, isOpenEye);
        this.isOpenEye = isOpenEye;

        setTopTotalAsset(mAllAssetResponse);

        assetListAdapter.setOpenEye(isOpenEye);
        assetListAdapter.notifyDataSetChanged();

    }


    /**
     * 搜索
     *
     * @param searchContent
     * @param isFilterZero
     */
    public void search(String searchContent, boolean isFilterZero) {
        if (!allTokensBalance.isEmpty()) {
            filterList.clear();
            for (AssetListResponse.BalanceBean BalanceBean : allTokensBalance) {

                if (isMatch(BalanceBean, searchContent, isFilterZero)) {
                    filterList.add(BalanceBean);
                }
            }

            assetListAdapter.setNewData(filterList);

        }
    }

    private boolean isMatch(AssetListResponse.BalanceBean balanceBean, String searchContent, boolean isFilterZero) {
        try {
            if (!TextUtils.isEmpty(searchContent)) {
                String token = balanceBean.getTokenId();
                String tokenName = balanceBean.getTokenName();
                if (!token.contains(searchContent) && !token.contains(searchContent.toUpperCase()) && !tokenName.contains(searchContent) && !tokenName.contains(searchContent.toUpperCase())) {
                    return false;
                }
            }
            if (isFilterZero) {
                String total = balanceBean.getBtcValue();
                if (!TextUtils.isEmpty(total)) {
                    double totald = Double.valueOf(total);
                    if (totald <= HIDE_MIN_BTC) {
                        return false;
                    }
                } else
                    return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.subAcountBtn:  //子账户
                IntentUtils.goCreateSubAccount(this);
                break;
            case R.id.transferBtn:  //划转
                IntentUtils.goAssetTransfer(this, "");
                break;
        }
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        refreshLayout.finishRefresh(1000);
        if (currentSubAccount != null) {
            getPresenter().getAccountList();
            getPresenter().getAccountAsset(currentSubAccount);
        }else{
            getPresenter().getAccountList();
        }
    }
}
